package com.attack.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;

/**
 * 防盗链过滤器
 * @author Administrator
 *
 */
@WebFilter(filterName = "safetyFilter", urlPatterns = "/imgs/*")
public class SafetyFilter implements Filter{
@Value("${base.name}")
private String baseName;
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		//1.获取请求头的referer字段的内容
		HttpServletRequest hsr=(HttpServletRequest)request;
		String referer =hsr.getHeader("referer");
		System.out.println(referer);
		if(StringUtils.isEmpty(referer)){
			request.getRequestDispatcher("/imgs/error.jpg").forward(request, response);
		}
		String domain =getDomain(referer);
		if(!baseName.equals(domain)){
			//2.比较获取的请求服务器的地址和设置服务器地址是不是一样的
			request.getRequestDispatcher("/imgs/error.jpg").forward(request, response);
		}
		chain.doFilter(request, response);
	}

	@Override
	public void destroy() {
		
	}
	
	/**
	 * 获取url对应的域名
	 *
	 * @param url
	 * @return
	 */
	public String getDomain(String url) {
		String result = "";
		int j = 0, startIndex = 0, endIndex = 0;
		for (int i = 0; i < url.length(); i++) {
			if (url.charAt(i) == '/') {
				j++;
				if (j == 2)
					startIndex = i;
				else if (j == 3)
					endIndex = i;
			}

		}
		result = url.substring(startIndex + 1, endIndex);
		return result;
	}

}
